<template>
  <div class="unit-conversion-management">
    <div class="page-header">
      <div class="header-left">
        <h2>单位换算管理</h2>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="showCreateDialog">
          <el-icon><Plus /></el-icon>新建转换规则
        </el-button>
        <el-button type="success" @click="showBulkImportDialog">
          <el-icon><Upload /></el-icon>批量导入
        </el-button>
      </div>
    </div>

    <!-- 查询条件 -->
    <div class="search-panel">
      <el-form :inline="true" :model="searchForm" class="search-form" @keyup.enter="handleSearch">
        <el-form-item label="源单位">
          <el-input v-model="searchForm.source_unit" placeholder="请输入源单位" />
        </el-form-item>
        <el-form-item label="目标单位">
          <el-input v-model="searchForm.target_unit" placeholder="请输入目标单位" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.is_active"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><RefreshRight /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 转换规则列表 -->
    <div class="table-container">
      <div class="batch-actions" v-if="selectedRules.length > 0">
        <el-button type="primary" @click="handleBatchEnable" :disabled="!hasDisabledRules">
          <el-icon><Check /></el-icon>批量启用
        </el-button>
        <el-button type="warning" @click="handleBatchDisable" :disabled="!hasEnabledRules">
          <el-icon><Close /></el-icon>批量禁用
        </el-button>
        <el-button type="danger" @click="handleBatchDelete">
          <el-icon><Delete /></el-icon>批量删除
        </el-button>
        <span class="selection-info">已选择 {{ selectedRules.length }} 项</span>
      </div>
      
      <el-table
        v-loading="loading.rules"
        :data="conversionRules"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="source_unit" label="源单位" min-width="120" />
        <el-table-column prop="target_unit" label="目标单位" min-width="120" />
        <el-table-column prop="conversion_formula" label="转换公式" min-width="180">
          <template #default="{ row }">
            <div class="formula-container">
              <span class="formula-text">{{ row.conversion_formula }}</span>
              <el-tooltip 
                placement="top" 
                effect="light"
                :content="`将${row.source_unit}转换为${row.target_unit}`" 
              >
                <el-popover
                  placement="top"
                  title="公式示例"
                  :width="200"
                  trigger="hover"
                >
                  <template #default>
                    <div class="formula-example">
                      <div class="example-row">
                        <span>1 {{ row.source_unit }} = {{ evaluateFormula(row.conversion_formula, 1) }} {{ row.target_unit }}</span>
                      </div>
                      <div class="example-row">
                        <span>5 {{ row.source_unit }} = {{ evaluateFormula(row.conversion_formula, 5) }} {{ row.target_unit }}</span>
                      </div>
                      <div class="example-row">
                        <span>10 {{ row.source_unit }} = {{ evaluateFormula(row.conversion_formula, 10) }} {{ row.target_unit }}</span>
                      </div>
                    </div>
                  </template>
                  <template #reference>
                    <el-button type="info" size="small" circle plain>
                      <el-icon><InfoFilled /></el-icon>
                    </el-button>
                  </template>
                </el-popover>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="130" show-overflow-tooltip />
        <el-table-column prop="created_at" label="创建时间" width="150">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="is_active" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'info'">
              {{ row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button-group class="operation-buttons">
              <el-button type="primary" @click="showEditDialog(row)">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button 
                :type="row.is_active ? 'warning' : 'success'" 
                @click="handleToggleStatus(row)"
              >
                <el-icon><SwitchButton /></el-icon>
                {{ row.is_active ? '禁用' : '启用' }}
              </el-button>
              <el-button type="danger" @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 创建/编辑转换规则对话框 -->
    <el-dialog
      v-model="dialogs.rule"
      :title="editingRule.id ? '编辑转换规则' : '新建转换规则'"
      width="550px"
    >
      <el-form
        ref="ruleFormRef"
        :model="editingRule"
        :rules="ruleRules"
        label-width="100px"
      >
        <el-form-item label="源单位" prop="source_unit">
          <el-input v-model="editingRule.source_unit" placeholder="请输入源单位" />
        </el-form-item>
        <el-form-item label="目标单位" prop="target_unit">
          <el-input v-model="editingRule.target_unit" placeholder="请输入目标单位" />
        </el-form-item>
        <el-form-item label="转换公式" prop="conversion_formula">
          <el-input v-model="editingRule.conversion_formula" placeholder="请输入转换公式，如 x * 2">
            <template #prepend>
              <span>x = </span>
            </template>
          </el-input>
          <div class="form-tip">转换公式中使用变量x表示源单位的值，如：x * 2表示乘以2；x / 1000表示除以1000</div>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="editingRule.description" 
            type="textarea" 
            :rows="2" 
            placeholder="请输入描述，例如：克转千克"
          />
        </el-form-item>
        <el-form-item label="状态" prop="is_active">
          <el-switch
            v-model="editingRule.is_active"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogs.rule = false">取消</el-button>
          <el-button type="primary" :loading="loading.submit" @click="handleSubmitRule">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量导入对话框 -->
    <el-dialog
      v-model="dialogs.bulkImport"
      title="批量导入转换规则"
      width="600px"
    >
      <div class="bulk-import-dialog">
        <el-alert
          type="info"
          show-icon
          :closable="false"
          title="请按照JSON格式输入转换规则数据"
        />
        <p class="format-example">格式示例：<code>[{"source_unit": "克", "target_unit": "千克", "conversion_formula": "x / 1000", "description": "克转千克"}]</code></p>
        <el-input
          v-model="bulkImportData"
          type="textarea"
          :rows="10"
          placeholder="请输入JSON格式的转换规则数据"
          @input="validateBulkImportData"
        />
        <div v-if="bulkImportError" class="json-error">
          <el-alert
            type="error"
            show-icon
            :closable="false"
            :title="bulkImportError"
          />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogs.bulkImport = false">取消</el-button>
          <el-button type="primary" :loading="loading.bulkImport" @click="handleBulkImport">
            导入
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, Edit, Delete, Search, RefreshRight, Upload, SwitchButton, InfoFilled, Check, Close
} from '@element-plus/icons-vue'
import { 
  getUnitConversionList, 
  createUnitConversion, 
  updateUnitConversion, 
  deleteUnitConversion,
  deleteConversionRule
} from '@/api/config'

// 搜索表单
const searchForm = reactive({
  source_unit: '',
  target_unit: '',
  is_active: ''
})

// 状态变量
const conversionRules = ref([])
const selectedRules = ref([])
const editingRule = ref({
  source_unit: '',
  target_unit: '',
  conversion_formula: '',
  description: '',
  is_active: true
})
const bulkImportData = ref('')
const bulkImportError = ref('')

// 加载状态
const loading = reactive({
  rules: false,
  submit: false,
  bulkImport: false
})

// 对话框显示状态
const dialogs = reactive({
  rule: false,
  bulkImport: false
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表单引用
const ruleFormRef = ref(null)

// 表单验证规则
const ruleRules = {
  source_unit: [
    { required: true, message: '请输入源单位', trigger: 'blur' }
  ],
  target_unit: [
    { required: true, message: '请输入目标单位', trigger: 'blur' }
  ],
  conversion_formula: [
    { required: true, message: '请输入转换公式', trigger: 'blur' },
    { 
      pattern: /^[x\s\d+\-*/().]+$/, 
      message: '公式格式错误，只能包含x、数字和运算符', 
      trigger: 'blur' 
    }
  ]
}

// 计算属性
const hasEnabledRules = computed(() => {
  if (selectedRules.value.length === 0) return false;
  // 检查选择的规则中是否有启用状态的规则
  return selectedRules.value.some(rule => rule.is_active);
})

const hasDisabledRules = computed(() => {
  if (selectedRules.value.length === 0) return false;
  // 检查选择的规则中是否有禁用状态的规则
  return selectedRules.value.some(rule => !rule.is_active);
})

// 初始化
onMounted(() => {
  fetchConversionRules()
})

// 获取转换规则列表
const fetchConversionRules = async () => {
  try {
    loading.rules = true
    
    // 构建查询参数
    const params = {
      page: pagination.currentPage,
      page_size: pagination.pageSize
    }
    
    if (searchForm.source_unit) {
      params.source_unit = searchForm.source_unit
    }
    
    if (searchForm.target_unit) {
      params.target_unit = searchForm.target_unit
    }
    
    if (searchForm.is_active !== '') {
      params.is_active = searchForm.is_active
    }
    
    console.log('查询参数:', params)
    
    // 首先获取总数，不带分页参数
    try {
      const countParams = { ...params };
      delete countParams.page;
      delete countParams.page_size;
      const allRulesResponse = await getUnitConversionList(countParams);
      console.log('所有规则数据:', allRulesResponse);
      
      // 计算实际的转换规则总数
      let totalRulesCount = 0;
      if (allRulesResponse && allRulesResponse.items) {
        allRulesResponse.items.forEach(unit => {
          if (unit.conversions && Array.isArray(unit.conversions)) {
            // 如果有search参数，需要过滤
            if (searchForm.source_unit || searchForm.target_unit || searchForm.is_active !== '') {
              unit.conversions.forEach(rule => {
                let match = true;
                if (searchForm.source_unit && !rule.source_unit.includes(searchForm.source_unit)) {
                  match = false;
                }
                if (searchForm.target_unit && !rule.target_unit.includes(searchForm.target_unit)) {
                  match = false;
                }
                if (searchForm.is_active !== '' && rule.is_active !== searchForm.is_active) {
                  match = false;
                }
                if (match) {
                  totalRulesCount++;
                }
              });
            } else {
              totalRulesCount += unit.conversions.length;
            }
          }
        });
      }
      pagination.total = totalRulesCount;
      console.log('计算得到的转换规则总数:', totalRulesCount);
    } catch (error) {
      console.error('获取总数失败:', error);
    }
    
    // 获取当前页数据
    const response = await getUnitConversionList(params);
    console.log('API返回数据:', response);
    
    if (response && response.items && Array.isArray(response.items)) {
      // 获取所有转换规则并扁平化
      const allRules = [];
      response.items.forEach(unit => {
        if (unit.conversions && unit.conversions.length > 0) {
          unit.conversions.forEach(rule => {
            // 过滤条件
            let match = true;
            if (searchForm.source_unit && !rule.source_unit.includes(searchForm.source_unit)) {
              match = false;
            }
            if (searchForm.target_unit && !rule.target_unit.includes(searchForm.target_unit)) {
              match = false;
            }
            if (searchForm.is_active !== '' && rule.is_active !== searchForm.is_active) {
              match = false;
            }
            
            if (match) {
              allRules.push({
                ...rule,
                unit_id: unit.id
              });
            }
          });
        }
      });
      
      // 自己处理分页
      const startIndex = (pagination.currentPage - 1) * pagination.pageSize;
      const endIndex = startIndex + pagination.pageSize;
      conversionRules.value = allRules.slice(startIndex, endIndex);
      
      console.log(`分页处理：总共${allRules.length}条规则，显示${startIndex}到${endIndex}，实际显示${conversionRules.value.length}条`);
    } else if (Array.isArray(response)) {
      conversionRules.value = response;
      pagination.total = response.length;
    } else {
      conversionRules.value = [];
    }
    
    // 清空选中
    selectedRules.value = [];
  } catch (error) {
    console.error('获取转换规则列表失败:', error);
    ElMessage.error('获取转换规则列表失败');
    conversionRules.value = [];
    pagination.total = 0;
  } finally {
    loading.rules = false;
  }
}

// 显示创建对话框
const showCreateDialog = () => {
  editingRule.value = {
    source_unit: '',
    target_unit: '',
    conversion_formula: '',
    description: '',
    is_active: true
  }
  dialogs.rule = true
}

// 显示编辑对话框
const showEditDialog = (rule) => {
  editingRule.value = { ...rule }
  dialogs.rule = true
}

// 提交规则表单
const handleSubmitRule = async () => {
  try {
    await ruleFormRef.value.validate()
    
    loading.submit = true
    
    // 构建数据
    const data = {
      conversions: [
        {
          id: editingRule.value.id, // 如果是编辑现有规则，会有ID
          source_unit: editingRule.value.source_unit,
          target_unit: editingRule.value.target_unit,
          conversion_formula: editingRule.value.conversion_formula,
          description: editingRule.value.description,
          is_active: editingRule.value.is_active
        }
      ]
    }
    
    if (editingRule.value.id && editingRule.value.unit_id) {
      // 更新现有规则
      await updateUnitConversion(editingRule.value.unit_id, data)
      ElMessage.success('转换规则更新成功')
    } else {
      // 创建新规则
      await createUnitConversion(data)
      ElMessage.success('转换规则创建成功')
    }
    
    dialogs.rule = false
    fetchConversionRules()
  } catch (error) {
    console.error('保存转换规则失败:', error)
    ElMessage.error('保存转换规则失败: ' + (error.response?.data?.detail || error.message))
  } finally {
    loading.submit = false
  }
}

// 删除转换规则
const handleDelete = async (rule) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除从 "${rule.source_unit}" 到 "${rule.target_unit}" 的转换规则吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteConversionRule(rule.id)
    ElMessage.success('转换规则删除成功')
    fetchConversionRules()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除转换规则失败:', error)
      ElMessage.error('删除转换规则失败: ' + (error.response?.data?.detail || error.message))
    }
  }
}

// 切换转换规则状态
const handleToggleStatus = async (rule) => {
  try {
    const newStatus = !rule.is_active
    const actionText = newStatus ? '启用' : '禁用'
    
    await ElMessageBox.confirm(
      `确定要${actionText}从 "${rule.source_unit}" 到 "${rule.target_unit}" 的转换规则吗？`,
      `${actionText}确认`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: newStatus ? 'success' : 'warning'
      }
    )
    
    // 构建数据
    const data = {
      conversions: [
        {
          id: rule.id,
          is_active: newStatus
        }
      ]
    }
    
    await updateUnitConversion(rule.unit_id, data)
    ElMessage.success(`转换规则已${actionText}`)
    fetchConversionRules()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新转换规则状态失败:', error)
      ElMessage.error('更新转换规则状态失败: ' + (error.response?.data?.detail || error.message))
    }
  }
}

// 处理查询
const handleSearch = () => {
  pagination.currentPage = 1 // 重置到第一页
  fetchConversionRules()
}

// 重置查询
const resetSearch = () => {
  searchForm.source_unit = ''
  searchForm.target_unit = ''
  searchForm.is_active = ''
  pagination.currentPage = 1
  fetchConversionRules()
}

// 分页相关
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchConversionRules()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchConversionRules()
}

// 显示批量导入对话框
const showBulkImportDialog = () => {
  bulkImportData.value = ''
  bulkImportError.value = ''
  dialogs.bulkImport = true
}

// 验证批量导入数据
const validateBulkImportData = () => {
  if (!bulkImportData.value.trim()) {
    bulkImportError.value = ''
    return
  }
  
  try {
    const data = JSON.parse(bulkImportData.value)
    if (!Array.isArray(data)) {
      bulkImportError.value = '数据格式错误，应为数组'
      return
    }
    
    for (const item of data) {
      if (!item.source_unit || !item.target_unit || !item.conversion_formula) {
        bulkImportError.value = '部分数据缺少必填字段'
        return
      }
    }
    
    bulkImportError.value = ''
  } catch (error) {
    bulkImportError.value = '无效的JSON格式: ' + error.message
  }
}

// 处理批量导入
const handleBulkImport = async () => {
  try {
    validateBulkImportData()
    if (bulkImportError.value) {
      return
    }
    
    const rulesData = JSON.parse(bulkImportData.value)
    if (!rulesData.length) {
      ElMessage.warning('没有数据需要导入')
      return
    }
    
    loading.bulkImport = true
    
    // 分组规则按源单位
    const groupedRules = {}
    rulesData.forEach(rule => {
      if (!groupedRules[rule.source_unit]) {
        groupedRules[rule.source_unit] = {
          name: rule.source_unit,
          conversions: []
        }
      }
      
      groupedRules[rule.source_unit].conversions.push({
        source_unit: rule.source_unit,
        target_unit: rule.target_unit,
        conversion_formula: rule.conversion_formula,
        description: rule.description || '',
        is_active: rule.is_active !== false
      })
    })
    
    // 转换为数组格式
    const unitsData = Object.values(groupedRules)
    
    // 批量创建
    await createUnitConversion({ items: unitsData })
    ElMessage.success('转换规则批量导入成功')
    
    dialogs.bulkImport = false
    fetchConversionRules()
  } catch (error) {
    console.error('批量导入失败:', error)
    ElMessage.error('批量导入失败: ' + (error.response?.data?.detail || error.message))
  } finally {
    loading.bulkImport = false
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-';
  const date = new Date(dateStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  });
}

// 计算转换公式结果（用于预览）
const evaluateFormula = (formula, value) => {
  try {
    if (!formula) return '-';
    // 将x替换为具体数值，然后计算表达式
    const calculatedFormula = formula.replace(/x/g, value);
    return eval(calculatedFormula).toFixed(2);
  } catch (error) {
    console.error('公式计算错误:', error);
    return '计算错误';
  }
}

// 处理选择变化
const handleSelectionChange = (selected) => {
  selectedRules.value = selected
}

// 处理批量启用
const handleBatchEnable = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要批量启用选中的转换规则吗？',
      '批量启用确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }
    )
    
    // 按照unit_id分组规则
    const unitGroups = {};
    selectedRules.value.forEach(rule => {
      if (!rule.unit_id) {
        console.error('规则缺少unit_id:', rule);
        return;
      }
      
      if (!unitGroups[rule.unit_id]) {
        unitGroups[rule.unit_id] = [];
      }
      unitGroups[rule.unit_id].push(rule.id);
    });
    
    // 对每个单位分别发送请求
    for (const unitId in unitGroups) {
      const data = {
        conversions: unitGroups[unitId].map(id => ({
          id,
          is_active: true
        }))
      };
      console.log(`更新单位ID ${unitId} 的规则:`, data);
      await updateUnitConversion(unitId, data);
    }
    
    ElMessage.success('选中的转换规则已批量启用')
    fetchConversionRules()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量启用转换规则失败:', error)
      ElMessage.error('批量启用转换规则失败: ' + (error.response?.data?.detail || error.message))
    }
  }
}

// 处理批量禁用
const handleBatchDisable = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要批量禁用选中的转换规则吗？',
      '批量禁用确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 按照unit_id分组规则
    const unitGroups = {};
    selectedRules.value.forEach(rule => {
      if (!rule.unit_id) {
        console.error('规则缺少unit_id:', rule);
        return;
      }
      
      if (!unitGroups[rule.unit_id]) {
        unitGroups[rule.unit_id] = [];
      }
      unitGroups[rule.unit_id].push(rule.id);
    });
    
    // 对每个单位分别发送请求
    for (const unitId in unitGroups) {
      const data = {
        conversions: unitGroups[unitId].map(id => ({
          id,
          is_active: false
        }))
      };
      console.log(`更新单位ID ${unitId} 的规则:`, data);
      await updateUnitConversion(unitId, data);
    }
    
    ElMessage.success('选中的转换规则已批量禁用')
    fetchConversionRules()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量禁用转换规则失败:', error)
      ElMessage.error('批量禁用转换规则失败: ' + (error.response?.data?.detail || error.message))
    }
  }
}

// 处理批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要批量删除选中的 ${selectedRules.value.length} 条转换规则吗？此操作不可恢复。`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }
    )
    
    // 逐个删除规则
    for (const rule of selectedRules.value) {
      if (!rule.id) {
        console.error('规则缺少ID:', rule);
        continue;
      }
      console.log(`删除规则ID ${rule.id}`);
      await deleteConversionRule(rule.id);
    }
    
    ElMessage.success('选中的转换规则已批量删除')
    fetchConversionRules()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除转换规则失败:', error)
      ElMessage.error('批量删除转换规则失败: ' + (error.response?.data?.detail || error.message))
    }
  }
}
</script>

<style scoped>
.unit-conversion-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-panel {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.table-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.bulk-import-dialog {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.format-example {
  color: #606266;
  font-size: 14px;
}

.format-example code {
  background-color: #f5f7fa;
  padding: 2px 5px;
  border-radius: 3px;
  font-family: monospace;
}

.json-error {
  margin-top: 10px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  line-height: 1.2;
}

.formula-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.formula-text {
  font-family: monospace;
  background-color: #f5f7fa;
  padding: 2px 8px;
  border-radius: 3px;
  color: #409eff;
  font-weight: bold;
}

.formula-example {
  padding: 5px;
}

.example-row {
  margin-bottom: 8px;
  padding: 5px;
  background-color: #f5f7fa;
  border-radius: 3px;
  font-family: monospace;
  color: #303133;
}

.example-row:last-child {
  margin-bottom: 0;
}

.batch-actions {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.selection-info {
  margin-left: 10px;
  color: #606266;
  font-size: 14px;
}
</style> 